import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getStartToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

service.interceptors.request.use(async config => {
  if (store.getters.token) {
    const start = getStartToken()
    const now = Date.now()
    const hour = (now - start) / 1000 / 3600
    if (hour >= 1) {
      await store.dispatch('user/logout')
      Message.error('Token失效，请重新登录')
      router.push('/login')
      return
    }
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }

  return config
},
err => {
  return Promise.reject(err)
})

service.interceptors.response.use(res => {
  const data = res.data
  if (data.success) {
    Message({
      showClose: true,
      center: true,
      type: 'success',
      message: data.message
    })
    return data
  } else {
    return Promise.reject(data.message)
  }
},
async err => {
  if (err.response.data.code === 10002 && err.response.status === 401) {
    await store.dispatch('user/logout')
    Message.error(err.response.data.message)
    router.push('login')
  } else {
    return Promise.reject(err)
  }
})

export default service
